<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket AI 测试客户端</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 28px;
            margin-bottom: 10px;
        }
        
        .status {
            display: inline-block;
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: bold;
        }
        
        .status.connected {
            background: #10b981;
        }
        
        .status.disconnected {
            background: #ef4444;
        }
        
        .main {
            display: flex;
            height: 600px;
        }
        
        .chat-area {
            flex: 1;
            display: flex;
            flex-direction: column;
            border-right: 1px solid #e5e7eb;
        }
        
        .messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            background: #f9fafb;
        }
        
        .message {
            margin-bottom: 15px;
            animation: fadeIn 0.3s;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .message.user {
            text-align: right;
        }
        
        .message-content {
            display: inline-block;
            max-width: 70%;
            padding: 12px 16px;
            border-radius: 12px;
            word-wrap: break-word;
            white-space: pre-wrap;
        }
        
        .message.user .message-content {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .message.ai .message-content {
            background: white;
            border: 1px solid #e5e7eb;
            color: #1f2937;
        }
        
        .message.system .message-content {
            background: #fef3c7;
            color: #92400e;
            border: 1px solid #fbbf24;
        }
        
        .input-area {
            padding: 20px;
            background: white;
            border-top: 1px solid #e5e7eb;
        }
        
        .input-group {
            display: flex;
            gap: 10px;
            margin-bottom: 10px;
        }
        
        #messageInput {
            flex: 1;
            padding: 12px 16px;
            border: 2px solid #e5e7eb;
            border-radius: 12px;
            font-size: 14px;
            outline: none;
            transition: border-color 0.3s;
        }
        
        #messageInput:focus {
            border-color: #667eea;
        }
        
        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 12px;
            font-size: 14px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        .btn-secondary {
            background: #6b7280;
            color: white;
        }
        
        .options {
            display: flex;
            gap: 15px;
            align-items: center;
        }
        
        .checkbox-label {
            display: flex;
            align-items: center;
            gap: 5px;
            cursor: pointer;
        }
        
        .info-panel {
            width: 300px;
            padding: 20px;
            background: #f9fafb;
            overflow-y: auto;
        }
        
        .info-section {
            margin-bottom: 20px;
        }
        
        .info-section h3 {
            font-size: 14px;
            color: #6b7280;
            margin-bottom: 10px;
            text-transform: uppercase;
        }
        
        .info-item {
            padding: 10px;
            background: white;
            border-radius: 8px;
            margin-bottom: 8px;
            font-size: 12px;
        }
        
        .info-item strong {
            color: #374151;
            display: block;
            margin-bottom: 4px;
        }
        
        .trace-step {
            padding: 10px;
            background: white;
            border-left: 3px solid #667eea;
            border-radius: 4px;
            margin-bottom: 10px;
            font-size: 12px;
        }
        
        .trace-step .step-header {
            font-weight: bold;
            color: #667eea;
            margin-bottom: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🤖 WebSocket AI 测试客户端</h1>
            <span id="status" class="status disconnected">未连接</span>
        </div>
        
        <div class="main">
            <div class="chat-area">
                <div id="messages" class="messages"></div>
                
                <div class="input-area">
                    <div class="input-group">
                        <input type="text" id="messageInput" placeholder="输入消息..." />
                        <button class="btn btn-primary" onclick="sendMessage()">发送</button>
                    </div>
                    <div class="options">
                        <label class="checkbox-label">
                            <input type="checkbox" id="enableTracing" />
                            <span>启用溯源</span>
                        </label>
                        <button class="btn btn-secondary" onclick="clearMessages()">清空</button>
                    </div>
                </div>
            </div>
            
            <div class="info-panel">
                <div class="info-section">
                    <h3>连接信息</h3>
                    <div class="info-item">
                        <strong>会话ID:</strong>
                        <span id="sessionId">-</span>
                    </div>
                    <div class="info-item">
                        <strong>消息数:</strong>
                        <span id="messageCount">0</span>
                    </div>
                </div>
                
                <div class="info-section">
                    <h3>溯源链路</h3>
                    <div id="traceInfo">暂无溯源数据</div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="js/websocket-client.js"></script>
    <script>
        let client;
        let sessionId = null;
        let messageCount = 0;
        let currentMessage = '';
        
        // 初始化
        window.onload = function() {
            connectWebSocket();
            
            // 回车发送
            document.getElementById('messageInput').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    sendMessage();
                }
            });
        };
        
        // 连接 WebSocket
        function connectWebSocket() {
            const wsUrl = `ws://${window.location.host}/ws/ai`;
            client = new AIWebSocketClient(wsUrl);
            
            client.on('onOpen', () => {
                updateStatus('connected');
            });
            
            client.on('onMessage', (data) => {
                handleMessage(data);
            });
            
            client.on('onError', (error) => {
                updateStatus('disconnected');
                addSystemMessage('连接错误：' + error);
            });
            
            client.on('onClose', () => {
                updateStatus('disconnected');
            });
            
            client.connect();
        }
        
        // 发送消息
        function sendMessage() {
            const input = document.getElementById('messageInput');
            const content = input.value.trim();
            
            if (!content) return;
            
            const enableTracing = document.getElementById('enableTracing').checked;
            
            addMessage('user', content);
            client.sendChat(content, enableTracing);
            
            input.value = '';
            currentMessage = '';
        }
        
        // 处理接收到的消息
        function handleMessage(data) {
            if (data.type === 'system') {
                sessionId = data.sessionId;
                document.getElementById('sessionId').textContent = sessionId.substring(0, 8) + '...';
                addSystemMessage(data.content);
            } else if (data.type === 'message') {
                currentMessage += data.content;
                updateAIMessage(currentMessage);
            } else if (data.type === 'trace') {
                if (data.content) {
                    addMessage('ai', data.content);
                }
                if (data.metadata && data.metadata.step) {
                    addTraceStep(data.metadata.step, data.metadata.action, data.metadata.duration);
                }
            } else if (data.type === 'complete') {
                currentMessage = '';
            } else if (data.type === 'trace_complete') {
                currentMessage = '';
                if (data.metadata && data.metadata.summary) {
                    displayTraceSummary(data.metadata.summary);
                }
            } else if (data.type === 'error') {
                addSystemMessage('错误：' + data.error);
            }
        }
        
        // 添加消息
        function addMessage(type, content) {
            const messagesDiv = document.getElementById('messages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${type}`;
            messageDiv.innerHTML = `<div class="message-content">${escapeHtml(content)}</div>`;
            messagesDiv.appendChild(messageDiv);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
            
            messageCount++;
            document.getElementById('messageCount').textContent = messageCount;
        }
        
        // 添加系统消息
        function addSystemMessage(content) {
            addMessage('system', content);
        }
        
        // 更新 AI 消息（流式）
        function updateAIMessage(content) {
            const messagesDiv = document.getElementById('messages');
            let lastMessage = messagesDiv.lastElementChild;
            
            if (!lastMessage || !lastMessage.classList.contains('ai')) {
                addMessage('ai', content);
            } else {
                lastMessage.querySelector('.message-content').textContent = content;
                messagesDiv.scrollTop = messagesDiv.scrollHeight;
            }
        }
        
        // 添加溯源步骤
        function addTraceStep(step, action, duration) {
            const traceInfo = document.getElementById('traceInfo');
            if (traceInfo.textContent === '暂无溯源数据') {
                traceInfo.innerHTML = '';
            }
            
            const stepDiv = document.createElement('div');
            stepDiv.className = 'trace-step';
            stepDiv.innerHTML = `
                <div class="step-header">步骤 ${step}: ${action || ''}</div>
                ${duration ? `<div>耗时: ${duration}ms</div>` : ''}
            `;
            traceInfo.appendChild(stepDiv);
        }
        
        // 显示溯源总结
        function displayTraceSummary(summary) {
            const traceInfo = document.getElementById('traceInfo');
            
            const summaryDiv = document.createElement('div');
            summaryDiv.className = 'trace-step';
            summaryDiv.style.borderLeftColor = '#10b981';
            summaryDiv.innerHTML = `
                <div class="step-header">✅ 溯源完成</div>
                <div>总步骤: ${summary.totalSteps}</div>
                <div>总耗时: ${summary.totalDuration}ms</div>
            `;
            traceInfo.appendChild(summaryDiv);
        }
        
        // 清空消息
        function clearMessages() {
            document.getElementById('messages').innerHTML = '';
            document.getElementById('traceInfo').innerHTML = '暂无溯源数据';
            messageCount = 0;
            document.getElementById('messageCount').textContent = '0';
        }
        
        // 更新状态
        function updateStatus(status) {
            const statusEl = document.getElementById('status');
            if (status === 'connected') {
                statusEl.textContent = '已连接';
                statusEl.className = 'status connected';
            } else {
                statusEl.textContent = '未连接';
                statusEl.className = 'status disconnected';
            }
        }
        
        // HTML 转义
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
    </script>
</body>
</html>
